package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        PageHelper.startPage(studentQueryParam.getPage(),studentQueryParam.getPageSize());
        List<Student> studentList = studentMapper.list(studentQueryParam);
         Page<Student> p = (Page< Student>) studentList;
         return new PageResult<Student>(p.getTotal(),p.getResult());
    }

    @Override
    public void save(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insert(student);
    }

    @Override
    public Student getInfo(Integer id) {
         return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
         studentMapper.updateById(student);
    }

    @Override
    public void delete(List<Integer> ids) {
        //删除学生信息
        studentMapper.deleteByIds(ids);

    }

    @Override
    public void violation(Integer id, Integer score) {
        // 查询当前学员
        Student student = studentMapper.selectById(id);
        if (student == null) {
            throw new RuntimeException("学员不存在");
        }
        // 违纪次数+1，违纪扣分+score
        student.setViolationCount((short)(student.getViolationCount() + 1));
        student.setViolationScore((short)(student.getViolationScore() + score));


       studentMapper.update(student);
    }
}
